const express = require("express");
const router = express.Router();
const { messageModel } = require("../models/model");
// 存储消息记录
const messageStore = [];
// 发送消息
router.post('/send', (req, res) => {
  const { from, to, content } = req.body;
  const message = {
    id: Date.now(),
    from,
    to,
    content,
    timestamp: new Date(),
  };
  messageStore.push(message);
  res.json({
    code: 0,
    data: message,
    msg: 'success'
  });
});

// 获取历史消息
router.get('/history', (req, res) => {
  const { userId } = req.query;
  // 获取与指定用户相关的所有消息
  const messages = messageStore.filter(msg =>
      msg.from === userId || msg.to === userId
  );
  res.json({
    code: 0,
    data: messages,
    msg: 'success'
  });
});

// 获取所有用户消息列表（用于客服端）
router.get('/allMessages', (req, res) => {
  // 按用户分组获取最新消息
  const latestMessages = {};
  messageStore.forEach(msg => {
    const userId = msg.from === 'customer_service' ? msg.to : msg.from;
    if (!latestMessages[userId] || latestMessages[userId].timestamp < msg.timestamp) {
      latestMessages[userId] = {
        userId,
        title: `用户${userId}`,
        content: msg.content,
        time: new Date(msg.timestamp).toLocaleTimeString(),
        avatar: '/static/logo.png'
      };
    }
  });

  res.json({
    code: 0,
    data: Object.values(latestMessages),
    msg: 'success'
  });
});

module.exports = router;